<template>
    <div>
        <BasicTable @register="registerTable"
                    :rowSelection="rowSelection"
                    @edit-end="handleEditEnd"
                    @edit-cancel="handleEditCancel"
                    :beforeEditSubmit="beforeEditSubmit"
        >
            <!--插槽:table标题，表格顶部左侧区域，工具栏按钮 toolbar-->
            <template #tableTitle>
                <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleCreate"> 新增</a-button>
              <a-button type="primary" preIcon="ant-design:plus-outlined"  > 导入</a-button>
              <a-button type="primary" preIcon="ant-design:plus-outlined"  > 提交</a-button>
                <a-dropdown v-if="selectedRowKeys.length > 0">
                    <template #overlay>
                        <a-menu>
                            <a-menu-item key="1" @click="batchHandleDelete">
                                <Icon icon="ant-design:delete-outlined"></Icon>
                                删除
                            </a-menu-item>
                          <a-menu-item key="2" >
                            <Icon icon="ant-design:delete-outlined"></Icon>
                            提交
                          </a-menu-item>
                        </a-menu>
                    </template>
                    <a-button>批量操作
                        <Icon icon="mdi:chevron-down"></Icon>
                    </a-button>
                </a-dropdown>
            </template>
           <!-- 表格顶部右侧区域，默认为刷新、列配置等 -->
          <template #toolbar>
<!--            <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleCreate"> 导出</a-button>-->
          </template>
          <!--操作栏，行按钮，如何固定在右边？-->
          <template #action="{ record }">
              <TableAction :actions="getTableAction(record)"/>
          </template>
<!--          <template #action="{ record, column }">-->
<!--            <TableAction :actions="createActions(record, column)" />-->
<!--          </template>-->
          <!--展开行区域，显示展开行的描述等信息，如果使用了该插槽，则scoll（x和y）以及fix冻结失效-->
<!--          <template #expandedRowRender="{record}">-->
<!--            <div style="padding: 20px">-->
<!--              <span>状态描述: {{ record.description }}!</span>-->
<!--            </div>-->
<!--          </template>-->
          <!--表格顶部区域（标题上方）-->
          <template #headerTop>
            <div>状态管理</div>
          </template>

        </BasicTable>
    </div>
    <!-- 表单区域 -->
    <JeecgOrderModal @register="registerModal" @success="handleSuccess"></JeecgOrderModal>
</template>

<script lang="ts" name="tab-list" setup>
    //ts语法
    import {ref, computed, unref, watch, provide} from 'vue';
    import {BasicTable, TableAction} from '/@/components/Table';
    import {useListPage} from '/@/hooks/system/useListPage'
    import {useModal} from '/@/components/Modal';
    import JeecgOrderModal from './components/SysStatusModal.vue';
    import {columns, searchFormSchema} from './SysStatusEditCell-data';
    import {list, deleteOne, batchDelete, saveOrUpdate} from './SysStatus-api';
    import {useMessage} from "/@/hooks/web/useMessage";
    //消息框
    const { createMessage } = useMessage();
    //弹窗model
    const [registerModal, {openModal}] = useModal();

    // 列表页面公共参数、方法
    // canResize: false, 高度自适应？而非设置列宽可自定义调整
    const {tableContext} = useListPage({
        tableProps: {
            api: list,
          title:'状态管理',
            columns: columns,
            striped:true,
            bordered:true,
          clickToRowSelect:true,
            rowSelection: {type: 'checkbox'},
          scroll: {x:800, y:300},
          showTableSetting:true,
          tableSetting:{
            redo:true,
            size:true,
            setting:false,
            fullScreen:true,
          },
          showIndexColumn:true,
          useSearchForm:true,
            formConfig: {
                schemas: searchFormSchema,
            },
            actionColumn: {
                width: 180,
              fixed:'right',
            },
            pagination:{
                current: 1,
                pageSize: 5,
                pageSizeOptions: ['5', '10', '20'],
            },
        },
    });
    //注册table数据
    const [registerTable, {reload, updateTableDataRecord}, {rowSelection, selectedRowKeys}] = tableContext
    //当前选中的ID
    const orderId = computed(() => (unref(selectedRowKeys).length > 0 ? unref(selectedRowKeys)[0] : ''));

    //新增事件
    function handleCreate() {
        // openModal(true, {
        //     isUpdate: false,
        //     showFooter: true,
        // });
      saveOrUpdate({},false).then(()=>{
        reload();
      }).finally();
    }
    //点击√提交编辑内容
    //record内容为当前行中配置的列且不是hidden的（v-if的效果），如果需要ID，需要放到column中并设置列宽width=0，其中编辑单元格的值为修改前的值
    async function beforeEditSubmit({ record, index, key, value }) {
      console.log('单元格数据正在准备提交', { record, index, key, value });
      let params = {"id":record.id};
      params[key] = value;
      console.log('参数:',params);
      await saveOrUpdate(params,true);
    }
    //编辑完成后触发的事件
    //record为当前行的代理，列包含所有值，包括未定义到column中的列，编辑单元格的值为修改后的值
    function handleEditEnd({ record, index, key, value }: Recordable) {
      // console.log(record, index, key, value);
      console.log(record);
      //传递整行做更新
      // saveOrUpdate(record,true);
      return false;
    }
    //点击x取消编辑或者切换到其他行取消编辑时调用
    function handleEditCancel() {
      // console.log('cancel');
    }
    /**
     * 详情
     */
    async function handleDetail(record: Recordable) {
        openModal(true, {
            record,
            isUpdate: true,
            showFooter: false,
        });
    }

    /**
     * 删除事件
     */
    async function handleDelete(record) {
        await deleteOne({id: record.id}, reload);
    }

    /**
     * 批量删除事件
     */
    async function batchHandleDelete() {
        await batchDelete({ids: selectedRowKeys.value}, () => {
            selectedRowKeys.value = []
            reload()
        })
    }
    /**
     * 操作栏
     */
    function getTableAction(record) {
        return [
          {
            label: '查看',
            onClick: handleDetail.bind(null, record),
          },
          {
                label: '删除',
                popConfirm: {
                    title: '是否确认删除',
                    confirm: handleDelete.bind(null, record),
                },
            }
        ]
    }
</script>

<style scoped>

</style>
